package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.RegularConstant;
import cn.huiyunche.base.service.enums.*;
import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.*;
import cn.huiyunche.base.service.mappers.CDriverCertinfoMapper;
import cn.huiyunche.base.service.mappers.CTruckInfoMapper;
import cn.huiyunche.base.service.mappers.SUserInviteMapper;
import cn.huiyunche.base.service.mappers.ext.CTruckInfoViewMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.*;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service

public class TruckInfoServiceImpl implements TruckInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TruckInfoServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private CTruckInfoMapper cTruckInfoMapper = null;

    @Autowired
    private TruckAnnexService truckAnnexService = null;

    @Autowired
    private CDriverCertinfoMapper cDriverCertinfoMapper = null;

    @Autowired
    private SUserInviteMapper sUserInviteMapper = null;

    @Autowired
    private BActivityService bActivityService;

    @Autowired
    private CAccntTurnOverService cAccntTurnOverService = null;

    @Autowired
    private JPushService jPushService = null;

    @Autowired
    private UserDeviceService userDeviceService = null;

    @Autowired
    private CTruckInfoViewMapper cTruckInfoViewMapper = null;

    private CTruckInfoViewMapper getCTruckInfoViewMapper() {
        return this.cTruckInfoViewMapper;
    }

    private String save = "save";

    private String update = "update";

    private String defaultPicKey = "default.jpg";

    @Override
    public TruckInfoVo queryTruckInfo(Boolean truckType) throws Exception {
        logger.info("current class TruckInfoServiceImpl method queryTruckInfo");
        UserVo userVo = this.getUserService().getCurrentUserVo();
        logger.info("current userId " + userVo.getId());
        TruckInfoVo vo = new TruckInfoVo();
        CTruckInfoExample example = new CTruckInfoExample();
        example.createCriteria().andUserIdEqualTo(userVo.getId()).andTruckTypeEqualTo(truckType == null ? false : truckType);
        List<CTruckInfo> cInfos = this.getCTruckInfoMapper().selectByExample(example);
        if (CollectionUtils.isNotEmpty(cInfos) && cInfos.size() > 0) {
            CTruckInfo info = cInfos.get(0);
            BeanUtils.copyProperties(info, vo);
            List<TruckAnnexVo> certs = this.getTruckAnnexService().queryTruckAnnexList(info.getId());
            if (CollectionUtils.isNotEmpty(certs) && certs.size() > 0) {
                for (TruckAnnexVo truckAnnexVo : certs) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    // 驾驶
                    if (AnnexPicTypeEnum.JS.getValue().equals(truckAnnexVo.getPicType())) {
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        vo.setJsMap(map);
                    } else if (AnnexPicTypeEnum.XS.getValue().equals(truckAnnexVo.getPicType())) {// 行驶
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        vo.setXsMap(map);
                    } else if (AnnexPicTypeEnum.QY.getValue().equals(truckAnnexVo.getPicType())) {// 牵引
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        vo.setQyMap(map);
                    } else if (AnnexPicTypeEnum.GC.getValue().equals(truckAnnexVo.getPicType())) {// 挂车
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        vo.setGcMap(map);
                    }
                }
            }
            vo.setStatusText(TruckAuditStatusEnum.getByValue(vo.getStatus()).getText());
        } else {
            vo = null;
        }
        logger.info("current class TruckInfoServiceImpl method queryTruckInfo end......");
        return vo;
    }

    @Override
    public TruckInfoAdminVo queryTruckInfo(long id) throws Exception {
        logger.info("current class TruckInfoServiceImpl method queryTruckInfo start ......");
        CTruckInfo info = new CTruckInfo();
        try {
            info = this.getCTruckInfoMapper().selectByPrimaryKey(id);
        } catch (Exception e1) {
            logger.error("query truckinfo error : {}", e1);
            throw new BusinessException("查询车辆信息错误");
        }
        TruckInfoAdminVo vo = new TruckInfoAdminVo();
        if (info != null) {
            BeanUtils.copyProperties(info, vo);
            List<TruckAnnexVo> certs = this.getTruckAnnexService().queryTruckAnnexList(info.getId());
            if (CollectionUtils.isNotEmpty(certs) && certs.size() > 0) {
                for (TruckAnnexVo truckAnnexVo : certs) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    // 驾驶
                    if (AnnexPicTypeEnum.JS.getValue().equals(truckAnnexVo.getPicType())) {
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        map.put("desc", AnnexPicTypeEnum.JS.getText());
                        vo.setJsMap(map);
                    } else if (AnnexPicTypeEnum.XS.getValue().equals(truckAnnexVo.getPicType())) {// 行驶
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        map.put("desc", AnnexPicTypeEnum.XS.getText());
                        vo.setXsMap(map);
                    } else if (AnnexPicTypeEnum.QY.getValue().equals(truckAnnexVo.getPicType())) {// 牵引
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        map.put("desc", AnnexPicTypeEnum.QY.getText());
                        vo.setQyMap(map);
                    } else if (AnnexPicTypeEnum.GC.getValue().equals(truckAnnexVo.getPicType())) {// 挂车
                        map.put("key", truckAnnexVo.getPicKey());
                        map.put("url", QiniuUtils.generateDownloadTicket(truckAnnexVo.getPicKey(), ""));
                        map.put("desc", AnnexPicTypeEnum.GC.getText());
                        vo.setGcMap(map);
                    }
                }
            } else {
                for (AnnexPicTypeEnum temp : AnnexPicTypeEnum.values()) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("key", defaultPicKey);
                    map.put("url", QiniuUtils.generateDownloadTicket(defaultPicKey, ""));
                    if (AnnexPicTypeEnum.JS.getValue().equals(temp.getValue())) {
                        vo.setJsMap(map);
                    } else if (AnnexPicTypeEnum.XS.getValue().equals(temp.getValue())) {// 行驶
                        vo.setXsMap(map);
                    } else if (AnnexPicTypeEnum.QY.getValue().equals(temp.getValue())) {// 牵引
                        vo.setQyMap(map);
                    } else if (AnnexPicTypeEnum.GC.getValue().equals(temp.getValue())) {// 挂车
                        vo.setGcMap(map);
                    }
                }
            }
            SUser user = userService.getById(vo.getUserId());
            vo.setUserName(user.getRealName());
            vo.setTruckType(info.getTruckType());
            vo.setStatus(info.getStatus());
        }
        logger.info("current class TruckInfoServiceImpl method queryTruckInfo end ......");
        return vo;
    }

    @Override
    public Map<String, Object> list(PageVo page) throws Exception {
        page.setTotalRecord(this.getCTruckInfoViewMapper().countByExample());
        List<DriverTruckInfoVo> vos = this.getCTruckInfoViewMapper().selectByExample(page);
        Map<String, Object> map = new HashMap<String, Object>();
        if (CollectionUtils.isNotEmpty(vos)) {
            vos.stream().forEach(item -> {
                if (null != item && StringUtils.isNotBlank(item.getIdno())) {
                    try {
                        item.setIdno(HYCUtils.decryptBankCard(item.getIdno()));
                    } catch (Exception e) {
                        item.setIdno("");
                        logger.error("HYCUtils.decryptBankCard error: {}", e);
                    }
                }
            });
        }
        map.put("truckInfo", vos);
        map.put("page", page);
        return map;
    }

    @Override
    public Integer currentUserTruckStatus(Boolean truckType) throws Exception {
        logger.info("class TruckInfoServiceImpl method currentUserTruckStatus start ...... params: {}", truckType);
        UserVo user = this.getUserService().getCurrentUserVo();
        logger.info("current userid : " + user.getId());
        CTruckInfoExample search = new CTruckInfoExample();
        CTruckInfoExample.Criteria criteria = search.createCriteria();
        criteria.andUserIdEqualTo(user.getId()).andTruckTypeEqualTo(truckType == null ? false : truckType);
        List<CTruckInfo> truckInfoList = new ArrayList<CTruckInfo>();
        try {
            truckInfoList = this.getCTruckInfoMapper().selectByExample(search);
        } catch (Exception e) {
            logger.error("selectByExample error : {}", e);
            throw new BusinessException("数据加载错误");
        }
        if (CollectionUtils.isNotEmpty(truckInfoList) && truckInfoList.size() > 0) {
            Integer flg = truckInfoList.get(0).getStatus();
            logger.info("current user truck status : " + flg);
            return flg;
        }
        logger.info("class TruckInfoServiceImpl method currentUserTruckStatus end ......");
        return null;
    }

    @Override
    public long add(TruckInfoVo truckInfoVo) throws Exception {
        this.validation(truckInfoVo, save);
        UserVo userVo = this.getUserService().getCurrentUserVo();
        CTruckInfoExample search = new CTruckInfoExample();
        search.createCriteria().andTractorNumberEqualTo(truckInfoVo.getTractorNumber()).andTruckTypeEqualTo(truckInfoVo.getTruckType() == null ? false : truckInfoVo.getTruckType());
        List<CTruckInfo> truckInfos = this.getCTruckInfoMapper().selectByExample(search);
        if (CollectionUtils.isNotEmpty(truckInfos) && truckInfos.size() > 0) {
            logger.info("The data already exists");
            if (truckInfoVo.getTruckType()) {
                throw new BusinessException("车牌号已存在");
            }
            throw new BusinessException("此牵引车车牌号已存在");
        }
        if (null == truckInfoVo.getTruckType() || !truckInfoVo.getTruckType()) {
            CTruckInfoExample example = new CTruckInfoExample();
            example.createCriteria().andTrailerNumberEqualTo(truckInfoVo.getTrailerNumber());
            List<CTruckInfo> examples = this.getCTruckInfoMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(examples) && examples.size() > 0) {
                logger.info("The data already exists");
                throw new BusinessException("此挂车车牌号已存在");
            }
        }
        CTruckInfo truckInfo = new CTruckInfo();
        BeanUtils.copyProperties(truckInfoVo, truckInfo);
        truckInfo.setUserId(userVo.getId());
        truckInfo.setTractorNumber(truckInfo.getTractorNumber().toUpperCase());
        truckInfo.setTrailerNumber(StringUtils.isNotBlank(truckInfo.getTrailerNumber()) ? truckInfo.getTrailerNumber().toUpperCase() : "");
        truckInfo.setStatus(TruckAuditStatusEnum.AUDIT_CENTER.getValue());
        this.getCTruckInfoMapper().insertSelective(truckInfo);
        for (AnnexPicTypeEnum typeEnum : AnnexPicTypeEnum.values()) {
            CTruckCert cert = null;
            if (null == truckInfoVo.getTruckType() || !truckInfoVo.getTruckType()) {
                if (AnnexPicTypeEnum.JS.getValue().equals(typeEnum.getValue())) {//驾驶
                    cert = this.buildCtruck(truckInfoVo.getJsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.XS.getValue().equals(typeEnum.getValue())) {// 行驶
                    cert = this.buildCtruck(truckInfoVo.getXsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.QY.getValue().equals(typeEnum.getValue())) {// 牵引
                    cert = this.buildCtruck(truckInfoVo.getQyKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.GC.getValue().equals(typeEnum.getValue())) {// 挂车
                    cert = this.buildCtruck(truckInfoVo.getGcKey(), typeEnum.getValue(), truckInfo.getId());
                }
            } else {
                if (AnnexPicTypeEnum.JS.getValue().equals(typeEnum.getValue())) {//驾驶
                    cert = this.buildCtruck(truckInfoVo.getJsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.XS.getValue().equals(typeEnum.getValue())) {// 行驶
                    cert = this.buildCtruck(truckInfoVo.getXsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.QY.getValue().equals(typeEnum.getValue())) {// 牵引
                    cert = this.buildCtruck(truckInfoVo.getQyKey(), typeEnum.getValue(), truckInfo.getId());
                }
            }
            if (null != cert) {
                this.getTruckAnnexService().add(cert);
            }
        }
        CDriverCertinfoExample dExample = new CDriverCertinfoExample();
        dExample.createCriteria().andUserIdEqualTo(userVo.getId());
        List<CDriverCertinfo> certinfos = this.getCDriverCertinfoMapper().selectByExample(dExample);
        if (CollectionUtils.isNotEmpty(certinfos) && certinfos.size() > 0) {
            CDriverCertinfo certinfo = certinfos.get(0);
            certinfo.setStatus(TruckAuditStatusEnum.AUDIT_CENTER.getValue());
            this.getCDriverCertinfoMapper().updateByPrimaryKeySelective(certinfo);
        }
        return truckInfo.getId();
    }

    private CTruckCert buildCtruck(String picKey, String picType, Long truckId) {
        CTruckCert cert = new CTruckCert();
        cert.setPicDesc("-");
        cert.setPicItem("-");
        cert.setPicKey(picKey);
        cert.setPicType(picType);
        cert.setTruckId(truckId);
        cert.setUpdateTime(new Date());
        return cert;
    }

    @Override
    public long update(TruckInfoVo truckInfoVo) throws Exception {
        this.validation(truckInfoVo, update);
        CTruckInfoExample search = new CTruckInfoExample();
        search.createCriteria().andTractorNumberEqualTo(truckInfoVo.getTractorNumber()).andIdNotEqualTo(truckInfoVo.getId()).andTruckTypeEqualTo(truckInfoVo.getTruckType() == null ? false : truckInfoVo.getTruckType());
        List<CTruckInfo> truckInfos = this.getCTruckInfoMapper().selectByExample(search);
        if (CollectionUtils.isNotEmpty(truckInfos) && truckInfos.size() > 0) {
            logger.info("The data already exists");
            if (truckInfoVo.getTruckType()) {
                throw new BusinessException("车牌号已存在");
            }
            throw new BusinessException("此牵引车车牌号已存在");
        }
        if (null == truckInfoVo.getTruckType() || !truckInfoVo.getTruckType()) {
            CTruckInfoExample example = new CTruckInfoExample();
            example.createCriteria().andTrailerNumberEqualTo(truckInfoVo.getTrailerNumber()).andIdNotEqualTo(truckInfoVo.getId());
            List<CTruckInfo> examples = this.getCTruckInfoMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(examples) && examples.size() > 0) {
                logger.info("The data already exists");
                throw new BusinessException("此挂车车牌号已存在");
            }
        }
        UserVo userVo = this.getUserService().getCurrentUserVo();
        CTruckInfo truckInfo = new CTruckInfo();
        BeanUtils.copyProperties(truckInfoVo, truckInfo);
        truckInfo.setUserId(userVo.getId());
        truckInfo.setUpdateTime(new Date());
        truckInfo.setTractorNumber(truckInfo.getTractorNumber().toUpperCase());
        truckInfo.setTrailerNumber(StringUtils.isNotBlank(truckInfo.getTrailerNumber()) ? truckInfo.getTrailerNumber().toUpperCase() : "");
        truckInfo.setStatus(TruckAuditStatusEnum.AUDIT_CENTER.getValue());
        this.getCTruckInfoMapper().updateByPrimaryKeySelective(truckInfo);
        // 删除车辆附件
        this.getTruckAnnexService().del(truckInfoVo.getId());
        for (AnnexPicTypeEnum typeEnum : AnnexPicTypeEnum.values()) {
            CTruckCert cert = null;
            if (null == truckInfoVo.getTruckType() || !truckInfoVo.getTruckType()) {
                if (AnnexPicTypeEnum.JS.getValue().equals(typeEnum.getValue())) {// 驾驶
                    cert = this.buildCtruck(truckInfoVo.getJsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.XS.getValue().equals(typeEnum.getValue())) {// 行驶
                    cert = this.buildCtruck(truckInfoVo.getXsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.QY.getValue().equals(typeEnum.getValue())) {// 牵引
                    cert = this.buildCtruck(truckInfoVo.getQyKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.GC.getValue().equals(typeEnum.getValue())) {// 挂车
                    cert = this.buildCtruck(truckInfoVo.getGcKey(), typeEnum.getValue(), truckInfo.getId());
                }
            } else {
                if (AnnexPicTypeEnum.JS.getValue().equals(typeEnum.getValue())) {// 驾驶
                    cert = this.buildCtruck(truckInfoVo.getJsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.XS.getValue().equals(typeEnum.getValue())) {// 行驶
                    cert = this.buildCtruck(truckInfoVo.getXsKey(), typeEnum.getValue(), truckInfo.getId());
                } else if (AnnexPicTypeEnum.QY.getValue().equals(typeEnum.getValue())) {// 牵引
                    cert = this.buildCtruck(truckInfoVo.getQyKey(), typeEnum.getValue(), truckInfo.getId());
                }
            }
            if (null != cert) {
                this.getTruckAnnexService().add(cert);
            }
        }
        CDriverCertinfoExample dExample = new CDriverCertinfoExample();
        dExample.createCriteria().andUserIdEqualTo(userVo.getId());
        List<CDriverCertinfo> certinfos = this.getCDriverCertinfoMapper().selectByExample(dExample);
        if (CollectionUtils.isNotEmpty(certinfos) && certinfos.size() > 0) {
            CDriverCertinfo certinfo = certinfos.get(0);
            certinfo.setStatus(TruckAuditStatusEnum.AUDIT_CENTER.getValue());
            this.getCDriverCertinfoMapper().updateByPrimaryKeySelective(certinfo);
        }
        return truckInfoVo.getId();
    }

    private void validation(TruckInfoVo vo, String flg) throws Exception {
        if (update.equals(flg)) {
            if (vo.getId() == null) {
                logger.info("id is not null");
                throw new BusinessException("ID主键不能为空");
            }
        }
        if (null != vo.getTruckType() && vo.getTruckType()) { //同城
            if (StringUtils.isBlank(vo.getTractorNumber())) {
                logger.info("TractorNumber is not null");
                throw new BusinessException("车牌号不能为空");
            } else if (!vo.getTractorNumber().matches(RegularConstant.tractorNumber)) {
                logger.info("TractorNumber format error");
                throw new BusinessException("车牌号格式错误");
            }
        } else {
            if (StringUtils.isBlank(vo.getBoxTypeCode())) {
                logger.info("BoxTypeCode is not null");
                throw new BusinessException("箱体结构编码不能为空");
            } else if (StringUtils.isBlank(vo.getBoxTypeDesc())) {
                logger.info("BoxTypeDesc is not null");
                throw new BusinessException("箱体结构描述不能为空");
            } else if (StringUtils.isBlank(vo.getStoreNumberCode())) {
                logger.info("StoreNumberCode is not null");
                throw new BusinessException("仓位编码不能为空");
            } else if (StringUtils.isBlank(vo.getStoreNumberDesc())) {
                logger.info("StoreNumberDesc is not null");
                throw new BusinessException("仓位描述不能为空");
            } else if (StringUtils.isBlank(vo.getTractorNumber())) {
                logger.info("TractorNumber is not null");
                throw new BusinessException("牵引车车牌号不能为空");
            } else if (!vo.getTractorNumber().matches(RegularConstant.tractorNumber)) {
                logger.info("TractorNumber format error");
                throw new BusinessException("牵引车车牌号格式错误");
            } else if (StringUtils.isBlank(vo.getTrailerNumber())) {
                logger.info("TrailerNumber is not null");
                throw new BusinessException("挂车车牌号不能为空");
            } else if (!vo.getTrailerNumber().matches(RegularConstant.trailerNumber)) {
                logger.info("TractorNumber format error");
                throw new BusinessException("挂车车牌号格式错误");
            }
        }
    }

    /**
     * 车辆审核
     *
     * @param truckId
     * @param driverId
     * @param status    状态（10:审核中，20:审核未通过，30：审核已通过）
     * @param truckType
     * @return
     * @throws BusinessException
     */
    @Override
    public int auditUser(String truckId, String driverId, String status, Boolean truckType) throws Exception {
        if (StringUtils.isEmpty(truckId)) {
            logger.info("truckId is not null");
            throw new BusinessException("车辆ID不能为空");
        } else if (StringUtils.isEmpty(status)) {
            logger.info("status is not null");
            throw new BusinessException("状态不能为空");
        } else if (StringUtils.isBlank(driverId)) {
            logger.info("driverId is not null");
            throw new BusinessException("司机ID不能为空");
        }
        // CTruckInfo info = new CTruckInfo();
        CTruckInfoExample truckInfoExample = new CTruckInfoExample();
        truckInfoExample.createCriteria().andIdEqualTo(Long.valueOf(truckId));
        CTruckInfo info = this.getCTruckInfoMapper().selectByExample(truckInfoExample).get(0);
        info.setStatus(TruckAuditStatusEnum.getByValue(Integer.valueOf(status)).getValue());

        try {
            try {
                this.getCTruckInfoMapper().updateByPrimaryKeySelective(info);
                CDriverCertinfo cInfo = this.getCDriverCertinfoMapper().selectByPrimaryKey(Long.valueOf(driverId));
                SUserDevices device = this.getUserDeviceService().getUserLastDevice(Long.valueOf(cInfo.getUserId()));
                List<String> lists = new ArrayList<String>();
                if (device != null && !"".equals(device.getUuid())) {
                    lists.add(device.getUuid().replaceAll("-", "").replaceAll("_", ""));
                }
                if (TruckAuditStatusEnum.AUDIT_NOT_PASS.getValue() == Integer.valueOf(status)) {
                    if (truckType) {
                        this.getJPushService().sendMsgStanCityByAliases(lists, "您的身份认证被拒绝,请您重新提交身份认证信息!", "0");
                    } else {
                        this.getJPushService().sendMsgStanByAliases(lists, "您的身份认证被拒绝,请您重新提交身份认证信息!", "0");
                    }
                } else if (TruckAuditStatusEnum.AUDIT_PASS.getValue() == Integer.valueOf(status)) {
                    if (truckType) {
                        this.getJPushService().sendMsgStanCityByAliases(lists, "您的身份认证已通过,您现在可以上线接单啦!", "1");
                    } else {
                        this.getJPushService().sendMsgStanByAliases(lists, "您的身份认证已通过,您现在可以上线接单啦!", "1");
                    }
                }
            } catch (Exception e) {
                logger.error("update truckinfo error : {}", e);
                throw new BusinessException("更新车辆信息异常");
            }
            CDriverCertinfo certinfo = new CDriverCertinfo();
            certinfo.setId(Long.valueOf(driverId));
            certinfo.setStatus(TruckAuditStatusEnum.getByValue(Integer.valueOf(status)).getValue());
            try {
                this.getCDriverCertinfoMapper().updateByPrimaryKeySelective(certinfo);
            } catch (Exception e) {
                logger.error("update driverCertinfo error : {}", e);
                throw new BusinessException("更新司机信息异常");
            }

            // 司机认证通过 向(司机)账户增加余额
            this.addDriverCerBalance(info.getUserId());

            // 司机认证通过 向(司机)账户增加积分余额
            // this.getBScoresTurnoverService().addDiscountScores(info.getUserId(), UserTypeEnum.DRIVER.getValue());

            CDriverCertinfo certinfo2 = this.getCDriverCertinfoMapper().selectByPrimaryKey(Long.valueOf(driverId));
            if (certinfo2 != null) {
                SUser user = this.getUserService().getById(certinfo2.getUserId());
                SUserInviteExample example = new SUserInviteExample();
                if (user.getInvitedCode() != null) {
                    example.createCriteria().andInviteCodeEqualTo(user.getInvitedCode());

                    List<SUserInvite> sInvites = this.getSUserInviteMapper().selectByExample(example);
                    if (CollectionUtils.isNotEmpty(sInvites) && sInvites.size() > 0) {
                        SUserInvite sInvite = sInvites.get(0);
                        sInvite.setInviteCount(sInvite.getInviteCount() == null ? 1 : sInvite.getInviteCount() + 1);
                        this.getSUserInviteMapper().updateByPrimaryKeySelective(sInvite);

                        // 司机认证通过 向(公司)账户增加余额
                        this.addCompanyBalance(sInvite.getUserId());
                    }
                }

            }
        } catch (Exception e) {
            logger.error("audituser error : {}", e);
            throw new BusinessException("司机认证异常");
        }
        return 0;
    }

    // 司机认证通过 向(公司)账户增加余额
    public void addCompanyBalance(Long CompanyId) {
        logger.info("driver auth pass add balance params CompanyId : {}", CompanyId);
        try {
            SUser sUser = this.getUserService().getById(Long.valueOf(CompanyId));

            List<CTurnover> cTurnovers = new ArrayList<CTurnover>();
            CTurnover cTurnover = new CTurnover();
            cTurnover.setUserId(sUser.getId());
            cTurnover.setUserName(sUser.getPhone());
            cTurnover.setUserType(sUser.getUserType());
            cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue());
            cTurnover.setPayType(AccPaytypeEnum.REGISTER.getValue());

            // 查询活动
            BActivity activity = bActivityService.getByRoleAndTypeAndClass(UserTypeEnum.COMPANY.getValue(), BActivityTypeEnum.REGISTER_GIFT.getValue(), BActivityClassEnum.CUT.getValue());
            if (null != activity) {
                cTurnover.setOrderId(activity.getId());    // 活动ID
                cTurnover.setOrderFee(activity.getSubsidy());
                cTurnover.setOrderActPay(activity.getSubsidy());
                cTurnover.setCreateTime(new Date());
                cTurnover.setUpdateTime(new Date());

                cTurnovers.add(cTurnover);

                this.getCAccntTurnOverService().addDetailsAndLedger(cTurnovers, 0);
            }
        } catch (Exception e) {
            logger.error("driver auth pass add balance error : {}", e);
            e.printStackTrace();
        }

    }

    // 司机认证通过 向(司机)账户增加余额
    public void addDriverCerBalance(Long driverId) {
        logger.info("driver auth pass add balance params driverId : {}", driverId);
        try {
            SUser sUser = this.getUserService().getById(Long.valueOf(driverId));

            List<CTurnover> cTurnovers = new ArrayList<CTurnover>();
            CTurnover cTurnover = new CTurnover();
            cTurnover.setUserId(sUser.getId());
            cTurnover.setUserName(sUser.getRealName());
            cTurnover.setUserType(sUser.getUserType());
            cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue());
            cTurnover.setPayType(AccPaytypeEnum.REGISTER.getValue());

            // 查询活动
            BActivity activity = bActivityService.getByRoleAndTypeAndClass(UserTypeEnum.DRIVER.getValue(), BActivityTypeEnum.REGISTER_GIFT.getValue(), BActivityClassEnum.CUT.getValue());
            if (null != activity) {
                cTurnover.setOrderId(activity.getId());    // 活动ID
                cTurnover.setOrderFee(activity.getSubsidy());
                cTurnover.setOrderActPay(activity.getSubsidy());
                cTurnover.setCreateTime(new Date());
                cTurnover.setUpdateTime(new Date());

                cTurnovers.add(cTurnover);

                this.getCAccntTurnOverService().addDetailsAndLedger(cTurnovers, 0);
            }
        } catch (Exception e) {
            logger.error("driver auth pass add balance error : {}", e);
            e.printStackTrace();
        }

    }

    @Override
    public CDriverCertinfo queryDriverInfo(long driverId) throws Exception {
        // CDriverCertinfoExample example = new CDriverCertinfoExample();
        // example.createCriteria().andUserIdEqualTo(driverId);
        // CDriverCertinfo info = this.getCDriverCertinfoMapper().selectByExample(example).get(0);
        CDriverCertinfo info = this.getCDriverCertinfoMapper().selectByPrimaryKey(driverId);
        try {
            info.setIdno(HYCUtils.decryptBankCard(info.getIdno()));
        } catch (Exception e) {
            logger.error("decrypt bank error : {}", e);
            throw new BusinessException("身份证号解密错误");
        }
        info.setIdpic1(QiniuUtils.generateDownloadTicket(info.getIdpic1(), ""));
        info.setIdpic2(QiniuUtils.generateDownloadTicket(info.getIdpic2(), ""));
        return info;
    }

    @Override
    public CDriverCertinfo queryDriverInfoByUserId(long driverId) throws Exception {
        CDriverCertinfoExample example = new CDriverCertinfoExample();
        example.createCriteria().andUserIdEqualTo(driverId);
        CDriverCertinfo info = this.getCDriverCertinfoMapper().selectByExample(example).get(0);
        try {
            info.setIdno(HYCUtils.decryptBankCard(info.getIdno()));
        } catch (Exception e) {
            logger.error("decrypt bank error : {}", e);
            throw new BusinessException("银行卡解密错误");
        }
        info.setIdpic1(QiniuUtils.generateDownloadTicket(info.getIdpic1(), ""));
        info.setIdpic2(QiniuUtils.generateDownloadTicket(info.getIdpic2(), ""));
        return info;
    }

    @Override
    public LayerTruckPicVo loadPic(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            logger.info("id is not null");
            throw new BusinessException("ID不能为空");
        }
        LayerTruckPicVo vo = new LayerTruckPicVo();
        vo.setId(id);
        vo.setStart("0");
        vo.setTitle("车辆、证照、身份证");
        PicVo picVo = null;
        List<CTruckCert> annexs = new ArrayList<CTruckCert>();
        try {
            annexs = this.getTruckAnnexService().loadPic(id);
        } catch (Exception e) {
            logger.error("select truckCert error : {}", e);
            throw new BusinessException("查询车辆附件信息错误");
        }
        List<PicVo> picVos = new ArrayList<PicVo>();
        if (CollectionUtils.isNotEmpty(annexs) && annexs.size() > 0) {
            for (CTruckCert truckAnnex : annexs) {
                String url = QiniuUtils.generateDownloadTicket(truckAnnex.getPicKey(), "");
                picVo = new PicVo();
                picVo.setAlt(truckAnnex.getPicDesc());
                picVo.setPid(truckAnnex.getId() + "");
                picVo.setSrc(url);
                picVo.setThumb(url + "?imageView2/2/h/150");
                picVos.add(picVo);
            }
        }
        vo.setData(picVos);
        return vo;
    }

    /**
     * 根据用户ID 查询当前用户车辆信息
     *
     * @param userId
     * @return
     */
    @Override
    public CDriverCertinfo queryDriverInfoById(Long userId) {
        CDriverCertinfoExample example = new CDriverCertinfoExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return this.getCDriverCertinfoMapper().selectByExample(example).get(0);
    }

    /**
     * 更具用户ID 查询当前车辆信息
     *
     * @param userId
     * @return
     */
    @Override
    public CTruckInfo queryTruckInfoById(Long userId) {
        CTruckInfoExample example = new CTruckInfoExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return this.getCTruckInfoMapper().selectByExample(example).get(0);
    }

    /**
     * 构建TruckAnnexVo
     *
     * @param truckAnnexVo
     * @return
     */
    /**
     * private void buildTruckAnnexVo(TruckInfoVo truckInfoVo) { // 车辆信息 List
     * <TruckAnnexVo> picList = null; Map<String, Object> truckPicMap = new
     * HashMap<String, Object>(); // 证照信息 Map<String, Object> licensePicMap =
     * new HashMap<String, Object>(); List<BCode> codes =
     * this.getCodeService().listPicCode(); TruckAnnexVo vo; if
     * (CollectionUtils.isNotEmpty(codes) && codes.size() > 0) { for
     * (TruckPicTypeEnum temp : TruckPicTypeEnum.values()) { picList = new
     * ArrayList<TruckAnnexVo>(); for (int i = 0; i < codes.size(); i++) { BCode
     * code = codes.get(i); vo = new TruckAnnexVo();
     * vo.setPicItem(code.getCode()); vo.setPicDesc(code.getName());
     * vo.setTruckId(truckInfoVo.getId()); if
     * (temp.getValue().equals(code.getClassCode())) {
     * vo.setPicType(temp.getValue()); picList.add(vo); } } if
     * (TruckPicTypeEnum.TRUCK.getValue().equals(temp.getValue())) {
     * truckPicMap.put("code", temp.getValue()); truckPicMap.put("name",
     * temp.getText()); truckPicMap.put("item", picList);
     * truckInfoVo.setTruckPicMap(truckPicMap); } else if
     * (TruckPicTypeEnum.LICENSE.getValue().equals(temp.getValue())) {
     * licensePicMap.put("code", temp.getValue()); licensePicMap.put("name",
     * temp.getText()); licensePicMap.put("item", picList);
     * truckInfoVo.setLicensePicMap(licensePicMap); } } } }
     **/

    /**
     * private void buildTruckAnnexVo1(List<TruckAnnexVo> vos, String flag, Long
     * truckInfoId) { List<String> strList = new ArrayList<String>(); for
     * (TruckAnnexVo truckAnnexVo : vos) {
     * strList.add(truckAnnexVo.getPicItem()); } // 车辆图片 List<BCode> codes =
     * this.getCodeService().listPicCode(); TruckAnnexVo vo; if
     * (CollectionUtils.isNotEmpty(codes) && codes.size() > 0) { for
     * (TruckPicTypeEnum temp : TruckPicTypeEnum.values()) { if
     * (temp.getValue().equals(flag)) { for (int i = 0; i < codes.size(); i++) {
     * BCode code = codes.get(i); if
     * (temp.getValue().equals(code.getClassCode()) &&
     * !strList.contains(code.getCode())) { vo = new TruckAnnexVo();
     * vo.setPicItem(code.getCode()); vo.setPicDesc(code.getName());
     * vo.setTruckId(truckInfoId); vo.setPicType(temp.getValue()); vos.add(vo);
     * } } } } } }
     **/

    private UserService getUserService() {
        return this.userService;
    }

    private CTruckInfoMapper getCTruckInfoMapper() {
        return this.cTruckInfoMapper;
    }

    private TruckAnnexService getTruckAnnexService() {
        return this.truckAnnexService;
    }

    private CDriverCertinfoMapper getCDriverCertinfoMapper() {
        return this.cDriverCertinfoMapper;
    }

    private SUserInviteMapper getSUserInviteMapper() {
        return this.sUserInviteMapper;
    }

    private CAccntTurnOverService getCAccntTurnOverService() {
        return this.cAccntTurnOverService;
    }

    private JPushService getJPushService() {
        return this.jPushService;
    }

    private UserDeviceService getUserDeviceService() {
        return this.userDeviceService;
    }
}